package com.jhd.fuzhou.view.receipt;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DoubleRandomService;
import com.jhd.fuzhou.service.PunishmentService;
import com.jhd.fuzhou.service.ReceiveService;
import com.jhd.fuzhou.util.AddReadPerson;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DialogSize;
import com.jhd.fuzhou.util.ReceiptProcess;
import com.jhd.fuzhou.util.SaveSupervisionInspection;
import com.jhd.fuzhou.util.StartProcess;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.view.punishment.AuditAdministrativeActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.ProInstance;
import com.jhd.fuzhou.vo.ReadPerson;
import com.jhd.fuzhou.vo.ReceiveReportVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;
import com.jhd.fuzhou.vo.SysUserVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.StartProcess.completeByAssign2;
import static com.jhd.fuzhou.util.StartProcess.start;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class AuditReceiptActivity extends BaseActivity {
    @BindView(R.id.rel_next_audit)RelativeLayout rel_next_audit;
    @BindView(R.id.tv_next_audit)TextView tv_next_audit;
    @BindView(R.id.lin_suggestion)LinearLayout lin_suggestion;
    @BindView(R.id.lin_reader)LinearLayout lin_reader;
    @BindView(R.id.et_suggestion)EditText et_suggestion;
    @BindView(R.id.rb_status_1)RadioButton rb_status_1;
    @BindView(R.id.rb_status_2)RadioButton rb_status_2;
    @BindView(R.id.btn_title)Button btn_title;
    @BindView(R.id.btn_post)Button btn_post;
    @BindView(R.id.rv_reader)RecyclerView rv_reader;
    private String data;
    private String message;//审核意见
    private String pass="1";//默认通过
    private Context context=this;
    private List<PersonInfoVo> personInfoVos;
    private ReceiveReportVo receiveReportVo;
    private List<SysUserVo> sysUserVoList;
    private List<SysUserVo> sysUserVoList3=new ArrayList<>();//去除被选择为下级审核人的人
    private String status,proInstance;
    private String username;
    private AlertDialog _alertDialog;
    Drawable drawable;
    private CheckAdapter adapter;
    private String checkPerson;
    private String[] readPersons;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_audit_receipt);
    }

    @Override
    protected void processLogic() {
        application.addTaskActivity(this);
        GridLayoutManager manager=new GridLayoutManager(context,3);
        rv_reader.setLayoutManager(manager);
        drawable = ContextCompat.getDrawable(context, R.mipmap.ic_must);
        // 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        data=getIntent().getStringExtra("data");
        status=getIntent().getStringExtra("status");
        proInstance=getIntent().getStringExtra("proInstance");
        receiveReportVo= JSON.parseObject(data, ReceiveReportVo .class);
        if("撤销审核".equals(status)){
            lin_suggestion.setVisibility(View.VISIBLE);btn_title.setCompoundDrawables(null, null, null, null);rel_next_audit.setVisibility(View.GONE);//左上右下
            lin_reader.setVisibility(View.GONE);
        }else{//审核
            if("办公室主任审核".equals(receiveReportVo.getProgress())){
                lin_reader.setVisibility(View.VISIBLE);
            }else{
                lin_reader.setVisibility(View.GONE);
            }
        }
        getSysUserListAll();
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCancel();
            }
        });
    }
    @OnClick({R.id.btn_post,R.id.btn_cancel,R.id.rb_status_1,R.id.rb_status_2,R.id.rel_next_audit})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_post:
                btn_post.setEnabled(false);
                HashMap map=new HashMap();
                map.put("pass",pass);
                if("审核".equals(status)){
                    if(pass.equals("2")){
                        if(StringUtil.isNullOrEmpty(et_suggestion.getText().toString().trim())){
                            CustomToast.showText(context,"请输入审核意见!",3000,0,0).show();
                        }else{
                            ReceiptProcess.backNodes(application,receiveReportVo,et_suggestion.getText().toString(),context);
                        }
                    }else{
                        if("请选择".equals(tv_next_audit.getText().toString())){
                            CustomToast.showText(context,"请选择下级审批人!",3000,0,0).show();
                        }else{
                            if("办公室主任审核".equals(receiveReportVo.getProgress())){
                                Map<String, Object> params = new LinkedHashMap<String, Object>();
                                params.put("id",receiveReportVo.getId());
                                params.put("username",application.getUserName());
                                params.put("checkPerson",checkPerson);
                                params.put("messageIsOpen",0);
                                List<String> list=new ArrayList<>();
                                if(sysUserVoList!=null){
                                    for (SysUserVo sysUserVo : sysUserVoList) {
                                        if(sysUserVo.isCheck()){
                                            list.add(sysUserVo.getUserName());
                                        }
                                    }
                                }
                                params.put("readPersons",list);
                                AddReadPerson.addReadPerson(application,context,JSON.toJSONString(params));
                            }
                            ReceiptProcess.completeByAssign(application,receiveReportVo,username,null,context);
                            //ReceiptProcess.getProInstanceId(application,administrativePunishmentVo.getId(),administrativePunishmentVo.getProgress(),null,username,context);
                        }
                    }
                }else if("撤销审核".equals(status)){
                    if(pass.equals("1")){//通过
                        save("已归档");//只有跳出流程后，将状态改为已归档
                    }else{//
                        ReceiptProcess.backNodes(application,receiveReportVo,et_suggestion.getText().toString(),context);
                    }
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btn_post.setEnabled(true);
                    }
                },3000);
                break;
            case R.id.btn_cancel:
                onCancel();
                break;
            case R.id.rb_status_1:
                if("审核".equals(status)){
                    lin_suggestion.setVisibility(View.GONE);rel_next_audit.setVisibility(View.VISIBLE);
                    if("办公室主任审核".equals(receiveReportVo.getProgress())){
                        lin_reader.setVisibility(View.VISIBLE);
                    }
                }else{
                    btn_title.setCompoundDrawables(null, null, null, null);lin_suggestion.setVisibility(View.VISIBLE);rel_next_audit.setVisibility(View.GONE);
                }
                pass="1";
                break;
            case R.id.rb_status_2:
                if("审核".equals(status)){
                    lin_suggestion.setVisibility(View.VISIBLE);rel_next_audit.setVisibility(View.GONE);
                    if("办公室主任审核".equals(receiveReportVo.getProgress())){
                        lin_reader.setVisibility(View.GONE);
                    }
                }else{
                    btn_title.setCompoundDrawables(drawable, null, null, null);lin_suggestion.setVisibility(View.VISIBLE);rel_next_audit.setVisibility(View.GONE);
                }
                pass="2";
                break;
            case R.id.rel_next_audit:
                dialogShow(tv_next_audit);
                break;
        }
    }

    public void dialogShow(TextView textView){
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_person_choose, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        DialogSize.setDialogSize(view,context);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        LinearLayout lin_parent = (LinearLayout) view.findViewById(R.id.lin_parent);
//        lin_parent.
        RecyclerView rv_choose = (RecyclerView) view.findViewById(R.id.rv_choose);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_choose.setLayoutManager(layoutManage);
        tv_title.setText("审批人");//标题要改一下
        EditText et_search = (EditText) view.findViewById(R.id.et_search);
        ImageView iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        List<SysUserVo> sysUserVoList2=new ArrayList<>();//用来展示的list
        SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList);
        rv_choose.setAdapter(recyclerAdapter);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sysUserVoList2.clear();
                if(!s.toString().equals("")){
                    iv_cancel.setVisibility(View.VISIBLE);
                }else{
                    iv_cancel.setVisibility(View.GONE);
                }
                for (SysUserVo sysUserVo : sysUserVoList) {
                    if(sysUserVo.getName().contains(s.toString())){
                        sysUserVoList2.add(sysUserVo);
                    }
                }
                SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList2);
                rv_choose.setAdapter(recyclerAdapter);
            }
        });
        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_search.setText("");iv_cancel.setVisibility(View.GONE);
                SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList);
                rv_choose.setAdapter(recyclerAdapter);
            }
        });
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());//使用这种方式更改了dialog的框宽
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    public class SupervisorAdapter extends RecyclerView.Adapter<SupervisorAdapter.ViewHolder> {
        private int checkPosition=-1;
        List<SysUserVo> sysUserVos;

        public SupervisorAdapter( List<SysUserVo> sysUserVos) {
            this.sysUserVos=sysUserVos;
        }

        @Override
        public SupervisorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            SupervisorAdapter.ViewHolder viewHolder = new SupervisorAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull SupervisorAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(sysUserVos.get(position).getName());
            if((sysUserVos.get(position).getName()+"("+sysUserVos.get(position).getDeptDesc()+")").equals(tv_next_audit.getText().toString())){
                holder.image.setVisibility(View.VISIBLE);
            }

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_next_audit.setText((sysUserVos.get(position).getName()+"("+sysUserVos.get(position).getDeptDesc()+")"));
                    username=sysUserVos.get(position).getUserName();
                    checkPerson=sysUserVos.get(position).getMobileNo();
                    sysUserVos.get(position).setCheck(false);//选中审核人，将阅文人的ischeck改为false
                    sysUserVoList3.clear();
                    for (SysUserVo sysUserVo : sysUserVoList) {
                        if(!sysUserVo.getId().equals(sysUserVos.get(position).getId())){
                            sysUserVoList3.add(sysUserVo);
                        }
                    }
                    _alertDialog.dismiss();
                    checkPosition=position;
                    notifyDataSetChanged();
                    adapter=new CheckAdapter(sysUserVoList3);
                    rv_reader.setAdapter(adapter);
                }
            });
            if(position==checkPosition){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                holder.image.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return sysUserVos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }

    public class CheckAdapter extends RecyclerView.Adapter<CheckAdapter.ViewHolder> {
        List<SysUserVo> sysUserVos;
        public CheckAdapter( List<SysUserVo> sysUserVos) {
            this.sysUserVos=sysUserVos;
        }

        @Override
        public CheckAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_enforce_basis, parent, false);
            CheckAdapter.ViewHolder viewHolder = new CheckAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull CheckAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(sysUserVos.get(position).getName());
            if(!sysUserVos.get(position).isReader()){
                holder.rb_radio.setButtonDrawable(R.drawable.selector_radiobutton);
            }else{
                holder.rb_radio.setButtonDrawable(R.drawable.selector_radiobutton_grey);
            }
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!sysUserVos.get(position).isReader()){
                        if(sysUserVos.get(position).isCheck()){
                            holder.rb_radio.setChecked(false);
                            sysUserVos.get(position).setCheck(false);//将阅文人的ischeck改为false
                            for (SysUserVo sysUserVo : sysUserVoList) {
                                if(sysUserVos.get(position).getId().equals(sysUserVo.getId())){
                                    sysUserVo.setCheck(false);
                                }
                            }
                        }else{
                            holder.rb_radio.setChecked(true);
                            sysUserVos.get(position).setCheck(true);//将阅文人的ischeck改为false
                            for (SysUserVo sysUserVo : sysUserVoList) {
                                if(sysUserVos.get(position).getId().equals(sysUserVo.getId())){
                                    sysUserVo.setCheck(true);
                                }
                            }
                        }
                    }
                }
            });
            if(sysUserVos.get(position).isCheck()){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return sysUserVos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }


    private void save(String reportStatus){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://192.168.1.94:9004/");//URL的头
        ReceiveService vs = retrofit.create(ReceiveService.class);
        receiveReportVo.setReportStatus(reportStatus);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(receiveReportVo));
        Call<JsonForResult> jsonForResultCall = vs.saveReceiveReport(application.getAccessToken(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        ReceiptProcess.completeByAssign(application,receiveReportVo,username,null,context);
                    } else {
                        CustomToast.showText(context, "保存收文失败！", 3000, 0, 0).show();
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public void onCancel() {
        Intent intent = new Intent();
        intent.putExtra("position","2");
        ((Activity)context).setResult(RESULT_OK, intent);
        ((Activity)context).finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onCancel();
        }
        return super.onKeyDown(keyCode, event);
    }


    /*获取审批人列表*/
    public void getSysUserListAll(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PunishmentService vs = retrofit.create(PunishmentService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getSysUserListAll(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            sysUserVoList= JSON.parseArray(jsonForResult.getData().toString(), SysUserVo.class);
                        }else{
                            sysUserVoList=new ArrayList<>();
                        }

                        if(receiveReportVo.getReadPersons()!=null){
                            readPersons=receiveReportVo.getReadPersons();
                            for (String readPerson : readPersons) {
                                for (SysUserVo sysUserVo : sysUserVoList) {
                                    if(readPerson.equals(sysUserVo.getUserName())){
                                        sysUserVo.setCheck(true);
                                        sysUserVo.setReader(true);
                                        break;
                                    }
                                }
                            }
                        }
                        adapter=new CheckAdapter(sysUserVoList);
                        rv_reader.setAdapter(adapter);

                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}